package com.spring.study.utils;

import io.minio.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import java.io.InputStream;


@Slf4j
@Component
public class MinioUtil {

    private String minioApi = "http://127.0.0.1:9000";
    private String accessKey = "LSAfzXWKMJD57n3XnwzW";
    private String secretKey = "HEba5EnBqhC6JatHOvpQIBOCDshk3tYdkxlplouP";

    public String uploadFile(InputStream  fileStream,Long fileSize, String minioFileName) throws Exception{
        String url;
        MinioClient minioClient = MinioClient.builder().endpoint(minioApi).credentials(accessKey,secretKey).build();

        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket("test").build());

        if (!bucketExists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket("test").build());
        }else {
            log.info("test bucket is exits");
        }

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("test")
                        .object(minioFileName)//上传到minio中文件的名字
                        .stream(fileStream,fileSize,-1)//本地需要上传的文件输入流
                        .contentType("image/"+minioFileName.split("\\.")[1])
                        .build());
        log.info("上传成功！");
        url=minioApi+"/test"+"/"+minioFileName;
        return url;
    }
//    public static void main(String[] args) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//
//        MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey,secretKey).build();
//
//        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket("test").build());
//
//        if (!bucketExists){
//            minioClient.makeBucket(MakeBucketArgs.builder().bucket("test").build());
//        }else {
//            log.info("test bucket is exits");
//        }
//
//        minioClient.uploadObject(
//                UploadObjectArgs.builder()
//                        .bucket("test")
//                        .object("picture1.png")//上传到minio中文件的名字
//                        .filename("C:\\Users\\11313\\Pictures\\1.png")//本地需要上传的文件路径
//                        .build());
//        log.info("上传成功！");
//    }
}
